package cn.itsource.basic.service;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.util.GetUserInfoUtil;
import cn.itsource.basic.util.PageList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

//@Service 千万不要加
@Transactional //事务
public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery> implements IBaseService<T, Q>{

    /**
     * 注入公共的mapper对象
     */
    @Autowired
    private Mapper<T> mapper;

    @Override
    @Transactional(readOnly = true) //只读，不需要事务
    public T findOne(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(readOnly = true) //只读，不需要事务
    public List<T> findAll() {
        return mapper.selectAll();
    }

    @Override
    public void saveOrUpdate(T t) {

        if (t.getId() == null){
            mapper.insertSelective(t);
        }else {
            mapper.updateByPrimaryKeySelective(t);
        }

    }

    @Override
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageList<T> findPage(Q q) {
        //1.使用分页插件
        PageHelper.startPage(q.getPage(),q.getSize());

        //2.执行查询方法
        List<T> ts = mapper.selectAll();

        //3.封装pageInfo
        PageInfo<T> pageInfo = new PageInfo<>(ts);

        //4.封装并返回分页对象
        return new PageList<>(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 批量删除
     * @param q
     */
    @Override
    public void batchDelete(Q q) {
        Long[] ids = q.getIds();
        if (ids != null && ids.length > 0){
            for (Long id : ids) {
                mapper.deleteByPrimaryKey(id);
            }
        }
    }
}
